#!/bin/csh -f
set echo_style=both
set commandline="$argv" # to save in INPUT/fig.cmdline
#PATHS
set SRCDIR=$DECAHOME/SRC
set EXEC=$DECAHOME/bin/fig_
set PHELP="awk -f $SRCDIR/pophelp.awk $SRCDIR/fig.help"
set LSOPT="$DECAHOME/scripts/lsopt fig"
set MODE=

#### FIG DEFAULTS
# paths
set FNAME="tiling.inp"
set PSOUT="fig.ps"
set XYZ_NAME="xyz.rel"
# boolean
set nofig=0
set title=1
set read_flags=0
set show_perp=0 #perp# [show_perp]
set show_tiling=0 #tiling# SHOW_TILING (connectivity pattern using default lw)
set show_tbonds=1 #tbonds# SHOW_TBONDS
set show_abonds=0 #abonds# BONDS-chem in A [ch1 ch2 orb1 orb2 length tol PScmd]
set show_atoms=1 #atoms# SHOW_ATOMS
set show_orbs=0 #orb# SHOW_ORBS
set show_xyz=0 #xyz#
set show_objects=0 #obj# OBJECTS
set sobj=
set NSO=0
set show_occ=0 #occ# [show occupancy for a chemistry] 
set advm=0
set orbl=0 #22# [Show orbit #]
set atl=0 #220# [Show atom #]
set atnl=0 #221# [Show atom_node labels]
set show_uc=0 #show_uc# [Show unit cell outline]
set show_mon=0 #fl# [show_mon]
set show_mon_mark=0 #???# [show_mon_mark] obsolete?
set show_sf=0 #sf# [show_sf]
set viewfrac=0 #???# [show only fraction of a viewport]
set pboxstroke=0
set arrow=0
set spin=0
# numeric
set perpdefs="4 -2 2 -1 1" #NOOPT# [SHOW_PERP: N_nu nu_1 ... nu_N]
set arrange="1 1" #arrange# ROWS and COLUMNS (on a single page)
set gap="0.01" #NOOPT# GAP (units of viewport) 
set zoom="0.9" #zoom# [ZOOM_FACTOR; zoom_in when > 1.0]
set uc="1 1" #uc# [include IMAGES of the unit cell]
set center="0.0 0.0" #14# [shift figure center (fraction of unit cell units)]
set zshift="0.0 0.0" #333# shift bonds with each subsequent tiling level
set fsize="0.15" #fsize# fontsize
set zwin="-0.5 0.5" #zwin# [z_min z_max inverse-interval]
set asizes="0.13 0.06" #asizes# [size(z_max) size(z_min) (edge-length units)]
set frac="1.0 1.0" #app# fractionX fractionY of the viewport [append opt 32]
set mft="1 1" #26# [show multi from # to #]
set lw="0.01" #30# [default thickness of the line (units of the edge)]
set bview="5.0"
set proj_xyz="1 2 3" #proj# (3=z) ATOMS-external
set x2y=0 #16# swap x2y
set adv=0 #23# [auto-advance (multi-UC mode)]
set suimp=0 #24# [SUPERIMPOSE: # of advances, new viewport AFTER tiling #]
set trep="0 3" #25# [REPEAT TILING #. Advance is set to false when repeating!]
set tnnl=0 #31# [show tiling_node nu]
set tnl=0 #310# [show tiling_node #]
set zlab=0
set eshow=0
set ecol=0
set zg=0
set zglim=0.02
set seed=1
set zpuck=0.0
set pmode=1

set test=0
set query=""
set fobj=0
set asp=0
set rcom=

######## set defaults from INPUT/FIG/defaults ########
set def="INPUT/FIG/defaults"
set argv_def=""
if ( -f $def ) then
    set argv_def=`awk 'NF>0{sub(/^ */,"");a=index($0,"#");c=$0;if(a>1){split($0,b,"#");c=b[1]}if(a!=1){cmd=cmd" -"c}}END{printf cmd}' $def`
#    echo "INPUT/FIG/defaults: $argv_def"
endif
########################### OPTIONS ###############################
set argv=($argv_def $argv)
####################  OPTIONS  ###################################
set defarrange=1
reprocess:
while ( "$*" != "" )
    switch ( $1 )
	case -r:
	    set rargv=`tail -1 INPUT/fig.cmdline|awk '$1=="fig"{sub(/^fig /,"");print $0}'`
	    set argv=($rargv)
	    set commandline=
	    goto reprocess
#	    echo $argv
#	    exit
	breaksw
	case -set:
	    shift
	    switch ( "$1" ) 
		case atoms:
		    shift
		    set show_atoms=$1
		breaksw
		case tiling:
		    shift
		    set show_tiling=$1
		breaksw
		case tbonds:
		    shift
		    set show_tbonds=$1
		breaksw
		case perp:
		    shift
		    set show_perp=$1
		breaksw
		case notitle:
		    set title=0
		breaksw
		case uco:
		    shift
		    set show_uc=$1
		breaksw
		case abonds:
		    shift
		    set show_abonds=$1
		breaksw
		case x2y:
		    shift
		    set x2y=$1
		breaksw
	    endsw
	breaksw
	case -perp:
	    @ show_perp = 1 - $show_perp
	    if (($show_perp == 1) && ($defarrange == 1)) then
		set arrange="2 2"
		set show_tiling=0
		set zoom=1.5
	    endif
	breaksw
	case -tinp:
	    shift
	    set MODE=$1
	breaksw
	case -nofig:
	    set nofig=1
	breaksw
	case -notitle:
	    set title=0
	breaksw
	case -tiling:
	    @ show_tiling = 1 - $show_tiling
	breaksw
	case -tbonds:
	    @ show_tbonds = 1 - $show_tbonds
	breaksw
	case -abonds:
	    @ show_abonds = 1 - $show_abonds
	breaksw
	case -fobj:
	    @ fobj = 1 - $fobj
	    set show_objects=$fobj
	    if( $fobj == 1 && !(-e INPUT/objects.fig) ) then
		echo "Option -fobj requires INPUT/objects.fig. Generate using mkdeco -fig DECOFILE."
		exit
	    endif
	breaksw
	case -atoms:
	    @ show_atoms = 1 - $show_atoms
	breaksw
	case -aspr: # aspect ratio Y/X
	    shift
	    set asp=$1
	breaksw
	case -orb:
	    set show_orbs=1
	breaksw
	case -allorb:
	    set show_orbs=2
	breaksw
	case -shift:
	    shift
	    set center=$1
	    shift
	    set center=$center" "$1
	breaksw
	case -fl:
	    set show_mon=1
	breaksw
	case -seed:
	    shift
	    set seed=$1
	breaksw
	case -xyz:
	    shift
	    set show_xyz=1
	    set XYZ_NAME=$1
	breaksw
	case -rxyz:
	    shift
	    set show_xyz=2
	    set XYZ_NAME=$1
	breaksw
	case -pxyz:
	    shift
	    set show_xyz=3
	    set XYZ_NAME=$1
	    shift
	    set zpuck=$1
	    shift
	    set pmode=$1
	    if($pmode != 1 && $pmode != 2) then
		echo "-pucker XYZ ZPUCK PMODE : bad value of PMODE : $pmode"
		exit
	    endif
	breaksw
	case -proj:
	    shift
	    set proj_xyz=`echo $1`
	    shift
	    set proj_xyz=`echo $proj_xyz" "$1`
	    shift
	    set proj_xyz=`echo $proj_xyz" "$1`
	breaksw
	case -obj:
	    @ show_objects = 1 - $show_objects
	breaksw
	case -so:
	    shift
	    set sobj=($sobj $1)
	    set show_objects = 1
	    @ NSO++
	breaksw
	case -occ:
	    shift
	    set show_occ="1 "$1
	breaksw
	case -arrow:
	    set set arrow=1
	breaksw
	case -zoom:
	    shift
	    set zoom=$1
	breaksw
	case -arrange:
	    shift
	    set arrange=$1
	    shift
	    set arrange=$arrange" "$1
	    set defarrange=1
	breaksw
	case -gap:
	    shift
	    set gap=$1
	breaksw
	case -uc:
	    shift
	    set uc=$1
	    shift
	    set uc=$uc" "$1	    
	breaksw
	case -uco:
	    @ show_uc = 1 - $show_uc
	breaksw
	case -fsize:
	    shift
	    set fsize=$1
	breaksw
	case -x2y:
	    @ x2y = 1 - $x2y
	breaksw
	case -zwin:
	    shift
	    set zwin=$1
	    shift
	    set zwin=$zwin" "$1
	breaksw
	case -asizes:
	    shift
	    set asizes=$1
	    shift
	    set asizes=$asizes" "$1
	breaksw
	case -pboxstroke:
	    @ pboxstroke = 1 - $pboxstroke
	breaksw
	case -pbox:
	    @ pboxstroke = 1 - $pboxstroke
	breaksw
	case -olab:
	    @ orbl = 1 - $orbl
	breaksw
	case -alab:
	    @ atl = 1 - $atl
	breaksw
	case -nalab:
	    @ atnl = 1 - $atnl
	breaksw
	case -zlab:
	    if( $show_xyz == 1 ) then
		set zlab = 2
	    else
		set zlab = 1
	    endif
	breaksw
	case -eshow:
	    set eshow = 1
	breaksw
	case -zg:
	    shift
	    set zglim=$1
	    set zg=1
	breaksw
	case -nlab:
	    @ tnl = 1 - $tnl 
	breaksw
	case -nnu:
	    @ tnnl = 1 - $tnnl
	breaksw
	case -sf:
	    @ show_sf = 1 - $show_sf
	breaksw
	case -adv:
	    set advm=1
	breaksw
	case -advm:
	    shift
	    set advm=$1
	breaksw
	case -lw:
	    shift
	    set lw=$1
	breaksw
	case -bview:
	    shift
	    set bview=$1
	breaksw
	case -q:
	    shift
	    set query=$1
	breaksw
	case -test:
	    set test=1
	breaksw
	case -f:
	    shift
	    set FNAME=$1
	breaksw
	case -h:
	    goto helpmessage
	breaksw
	case -help:
	    helpmessage:
	    shift
	    if ( $#argv == 0 ) then
		$LSOPT
		exit
	    endif
	    $PHELP $1
	    exit
	breaksw
	case -o:
	    shift
	    set PSOUT=$1
	breaksw
	default:
	    if ( -f "$1" ) then
		set FNAME="$1"
	    else
		echo 'Unrecognized option "'$1'". Available options: '
		$LSOPT
		exit
	    endif
	breaksw
    endsw
    shift
end

skip_options:
# INPUT/objects.def
if !( -e INPUT/objects.def ) then
    echo "fig: Input file INPUT/objects.def is required."
    exit
else
    set decotp=`awk 'FNR==5{print $1}' INPUT/objects.def`
    if ( $decotp == 0 ) then 
	set show_atoms=0
	if ( $show_perp == 1 ) set show_tiling=1
    endif
endif
if ( !( -e $FNAME ) && $query == "" ) then
    echo "Tiling/config $FNAME does not exist."
    exit
endif
if ( $show_xyz > 0 && !( -f $XYZ_NAME ) ) then
    echo "XYZ file $XYZ_NAME does not exist."
    exit
endif
if ( $show_xyz > 0 && $eshow > 0 ) then
    set ecol=`head -5 $XYZ_NAME|tail -1| awk '{ecol=0;number="^[+-]?([0-9]+[.]?[0-9]*|[.][0-9]+)$";if($6~number){ecol=6}else if($7~number){ecol=7};print ecol}'`
    if($ecol == 0) then
	echo "fig: XYZFILE $XYZ_NAME does not contain energy in col.6 or 7. Cant do eshow"
	set eshow=0
    endif
endif

# Compose INPUT/fig.inp
set out="INPUT/fig.inp"
if ( $test == 1 ) then
    set out="/dev/stdout"
    echo "%%%%%%%%%%%%%%%%%% output to INPUT/fig.inp : %%%%%%%%%%%%%%%%%%%%%%"
endif
if ( $test == 0 ) then
    echo "##### Generated by script fig #####" > $out
endif
# boolean
echo $PSOUT >> $out
echo $title" #title# " >> $out
echo $show_perp" "$perpdefs" #perp# [SHOW_PERP;  N_nu nu_1 ... nu_N]" >> $out
echo $nofig" #nofig# [dont export PS]" >> $out
echo $asp" #aspr# [aspect ratio; 0=default]" >> $out
echo $show_tiling" #tiling# [SHOW_TILING]" >> $out
echo $eshow" $ecol #eshow# [Show-site-ene from col 6]" >> $out
echo $show_xyz" {"$XYZ_NAME"} #xyz# [SHOW_XYZ]" >> $out
if ( $show_xyz > 0 ) then
    echo $proj_xyz" #proj# [XYZ PROJECTOR]" >> $out
endif
if ( $show_xyz == 3 ) then
    echo "$zpuck $pmode  # z-coordinate for a puckering layer to center on, show_scheme" >> $out
endif
echo $fobj" #fobj# [ADD INPUT/objects.fig]" >> $out
echo $show_occ" #occ# [SHOW_OCCUP]" >> $out
#echo $show_mon" #311# [show_mon] obsolete?"
#echo $show_mon_mark=0 #312# [show_mon_mark] obsolete?
echo $show_sf" #sf# [show stacking faults (circles)]" >> $out
#echo $viewfrac=0 #32# [show only fraction of a viewport]
#echo $frac" # [fractionX fractionY of the viewport (append opt 32)]"
echo $orbl" #olab# [Show orbit #]" >> $out
echo $atl" #alab# [Show atom #]" >> $out
echo $atnl" #nalab# [Show atom-node #s]" >> $out
echo "$zg $zglim #zg# display z-displacement in gray scale" >> $out
echo $zlab" #zlab# [Show-z-coord (2=relaxed xyz)]" >> $out
echo $tnnl" #nnu# [show tiling_node nu]" >> $out
echo $tnl" #nlab# [show tiling_node #]" >> $out
echo $x2y" #x2y# [swap x2y]" >> $out
echo $advm" #advm# advance vieport every advm-th tiling layer" >> $out
echo $show_uc" #uco# [Outline the unit cell]" >> $out 
# numeric
echo $lw" #lw# [default thickness of the line (units of the edge)]" >> $out
echo $bview" #bview# [viewport border thickness]" >> $out
echo $asizes" #asizes# [asize(z_max) asize(z_min) (edge-length units)]" >> $out
echo $pboxstroke" #pboxstroke# [outline box in perp-space?]" >> $out
echo $zwin" #zwin# [z_min z_max]" >> $out
echo $fsize" #fsize# [fontsize]" >> $out
echo $zoom" #zoom# [ZOOM; zoom_in for zoom > 1.0]" >> $out
echo $arrange" #arrange# [ROWS and COLUMNS (on a single page)]" >> $out
echo $gap" #gap# [gap between viewports on a single page]" >> $out
echo $uc" #uc# [ext_X ext_Y]" >> $out
echo $center" #shift# [shift figure center (fraction of unit cell units)]" >> $out
echo $zshift" #NOOPT# [shift tbonds with each subsequent tiling level]" >> $out
echo $mft" #NOOPT# [show multi from # to #]" >> $out
echo $suimp" #NOOPT# [SUPERIMPOSE: # of advances, new vport AFTER tiling #]" >> $out
echo $trep" #NOOPT# [REPEAT TILING #. Advance->false when repeating]" >> $out
echo $show_mon"  #fl# show flagged tiling nodes (copa.err)" >> $out
echo $arrow" # arrow # plot atoms displacement by arrow" >> $out
# PS ATOMS
if ( $show_atoms && -e INPUT/chps.def ) then
    awk 'BEGIN{n=0}{n++;a[n]=$0}END{print n, "[ATOM PS DEFS]"; for(i=1;i<=n;i++){print a[i]}}' INPUT/chps.def >> $out
    echo "* fig : atom plot definitions from chps.def"
else if ( $show_atoms && -e INPUT/FIG/atoms ) then
    awk 'BEGIN{n=0}/^</{n++;a[n]=substr($0,2)}END{print n, "[ATOM PS DEFS]"; for(i=1;i<=n;i++){print a[i]}}' INPUT/FIG/atoms >> $out
    echo "* fig : atom plot definitions from INPUT/FIG/atoms"
else
    echo "0 [ATOM PS DEFS]" >> $out
endif
if ( $show_xyz > 0 ) then
    if !( -f $XYZ_NAME ) then
	echo "Option -xyz: file $XYZ_NAME does not exist."
	exit
    endif 
    if ( -f INPUT/FIG/atoms_xyz ) then
awk 'BEGIN{n=0}/^</{n++;a[n]=substr($0,2)}END{print n, "[ATOM_XYZ PS DEFS]"; for(i=1;i<=n;i++){print a[i]}}' INPUT/FIG/atoms_xyz >> $out
    endif
endif
# PS ORBITS
if ( -e INPUT/orbps.def && $show_orbs == 1 ) then
    awk 'BEGIN{n=0}$1>0{n++;a[n]=$0}END{print n, "[ORBIT PS DEFS]"; for(i=1;i<=n;i++){print a[i]}}' INPUT/orbps.def >> $out
else if ( -e INPUT/FIG/colors.def && $show_orbs == 2 ) then
    awk 'BEGIN{n=0}$1>0{n++;a[n]=$1" 1.0 {"$3" "$4" "$5" rgb}"}END{print n, "[ORBIT PS DEFS]"; for(i=1;i<=n;i++){print a[i]}}' INPUT/FIG/colors.def >> $out
else
    echo "0 [ORBIT PS DEFS]" >> $out
endif

#PS tbonds
if ( $show_tbonds == 1 ) then
    if ( -e INPUT/FIG/tbonds ) then
	awk 'BEGIN{n=0}/^</{n++;a[n]=substr($0,2)}END{print n, "[TILING_BOND PS DEFS]"; for(i=1;i<=n;i++){print a[i]}}' INPUT/FIG/tbonds >> $out
    endif
else
    echo "0 [TILING_BOND PS DEFS]" >> $out
endif
#PS abonds
if ( $show_abonds == 1 ) then
    if ( -f INPUT/FIG/abonds ) then
	awk -f $DECAHOME/SRC/fig_parser.awk INPUT/FIG/abonds 0 >> $out
    endif
else
    echo "0 [ATOM_BOND PS DEFS]" >> $out
endif
#PS objects
if ( $show_objects == 1 ) then
    set o1=INPUT/FIG/objects
    set o2=INPUT/objps.def
    if ( -e $o1 || -e $o2 ) then
	if (! -e INPUT/FIG/objects ) set o1=
	if (! -e INPUT/objps.def ) set o2=
	awk -f $DECAHOME/SRC/fig_parser.awk $o2 $o1 $sobj $NSO >> $out
    endif
else
    echo "0 [OBJECT PS defs]" >> $out
endif
#random seed
echo "$seed  # seed # for random number generator" >> $out
if !( $query == "" ) then
    echo -n "Option "$query": "
    awk 'BEGIN{FS="#";item=ARGV[2];ARGC-=1;a="No value associated with "item"."}$2==item{a=$1}END{print a}' INPUT/fig.inp $query
    exit
endif

if($MODE == "") then # determine input mode automatically
    set MODE=`$DECAHOME/scripts/getmode $FNAME`
endif

#if( $MODE == 0 && $show_objects == 1 && $show_perp == 1 )then
#    echo "Cannot show objects in perp-view, unless atomic decoration was defined."
#    exit
#endif

### TITLE
if($title == 1) then
    if(-f figcap) then
	echo "fig: using custom figure title from file figcap"
	cp figcap INPUT/figcap.inp
    else
	echo -n $FNAME > INPUT/figcap.inp
	if($show_xyz > 0) then
	    echo "&$XYZ_NAME" >> INPUT/figcap.inp
	else
	    echo "" >>  INPUT/figcap.inp
	endif
    endif
endif

#set read_flags=`head -3 $FNAME|tail -1|awk '{for(i=1;i<=NF;i++){na=split($i,a,"=");if(na=2&&a[1]=="read_flags")print "1"}}'`
set dum=`grep read_flags $FNAME| wc -l`
if($dum == 1) set read_flags=1
set dum=`grep read_tvl $FNAME| wc -l`
if($dum == 1) set read_flags=1
set dum=`grep spin $FNAME| wc -l`
if($dum == 1) set read_flags=2
#echo READ_FLAGS $read_flags
#exit
if($read_flags == "") set read_flags=0
if ( $test == 0 ) then
    if ("$commandline" != "") echo "fig "$commandline >> INPUT/fig.cmdline
    echo $FNAME > .fig
    echo $MODE >> .fig
    echo $read_flags >> .fig
    cat .fig | $EXEC
    if(-f INPUT/onames.def && -f xyz.fig) then
	cat xyz.fig | awk 'BEGIN{fn="INPUT/onames.def";while(getline<fn){ol[$1]=$2}}FNR<5{print}FNR>4{printf("%13.8f %13.8f %13.8f %4i %4i  %s  %s\n",$1,$2,$3,$4,$5,ol[$5],$6)}' > xyz.$$
	mv xyz.$$ xyz.fig
    endif
else
    echo "%%%%%%%%%%%%%%%%%% pipe to fig_: %%%%%%%%%%%%%%%%%%%%%%%% "
    echo $FNAME\\n$MODE
endif
if($nofig == 1) rm fig.ps
##
